package cn.com.yinhex.util;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import ayou.util.DOC;
import ayou.util.UrlCacheMonitor;

public class VideoApi {
	static String[] youku_keys = { "XOTcy", "XNzAw", "XNjU2" };

	public static String getKey() {
		return youku_keys[(int) (Math.random() * youku_keys.length)];
	}

	public static DOC getMeta(String link) {
		DOC doc = new DOC();
		doc.put("swf_link", link);
		try {
			URL url = new URL(link);
			if (url.getHost().toLowerCase().endsWith(".youku.com")) {
				DOC ykdoc = getYouku(link);
				return ykdoc != null ? ykdoc : doc;
			}
			return doc;
		} catch (Exception e) {
			return doc;
		}
	}

	private static DOC getYouku(String link) throws Exception {
		// http://v.youku.com/v_show/id_XMjUxNzYwMjYw.html
		// http://player.youku.com/player.php/sid/XMjUxNzYwMjYw/v.swf
		// <embed
		// src="http://player.youku.com/player.php/sid/XMjUxNzYwMjYw/v.swf"
		// quality="high" width="480" height="400" align="middle"
		// allowScriptAccess="sameDomain"
		// type="application/x-shockwave-flash"></embed>
		Matcher m = Pattern.compile("[_\\/]([a-zA-Z0-9]{13})[\\.\\/_]").matcher(link);
		if (m.find()) {
			String id = m.group(1);
			String api_url = "http://api.youku.com/api_ptvideoinfo?id=" + id + "&rt=2&pid=" + getKey();
			String xml = UrlCacheMonitor.readCache(api_url, "UTF-8", 0).trim();
			SAXReader reader = new SAXReader(false);
			Document document = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
			Element root = document.getRootElement();
			Element item = root.element("item");
			DOC doc = new DOC();
			doc.put("html_link", item.elementTextTrim("playlink"));
			doc.put("swf_link", item.elementTextTrim("shareswf"));
			doc.put("title", item.elementTextTrim("title"));
			doc.put("image_link", item.elementTextTrim("imagelink"));
			doc.put("comment", item.elementTextTrim("comment"));
			doc.put("duration", item.elementTextTrim("duration"));
			doc.put("ptime", item.elementTextTrim("pubdate"));
			doc.put("userid", item.elementTextTrim("user"));
			doc.put("source", "�ſ�");
			return doc;
		}
		return null;
	}
}
